package com.pocketsweet.ui.uilib.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLArticleLike;
import com.pocketsweet.model.MLTopic;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.uilib.RoundedTransformationBuilder;
import com.pocketsweet.utils.ToolKits;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

/**
 *
 * @author Kam
 *
 */
public class RecommendArticleListAdapter extends BaseListAdapter<MLArticle> {
	private List<MLArticle> article;
	private List<MLTopic> mlTopic;
	private int likeCount = 0;
	private int i = 0;
	final int TYPE_ARTICLE = 1;

	public int oldCount = -1;

	public RecommendArticleListAdapter(Context ctx) {
		super(ctx);
	}

	public RecommendArticleListAdapter(Context ctx, List<MLArticle> datas) {
		super(ctx, datas);
	}

	public RecommendArticleListAdapter(Context ctx, List<MLArticle> datas,
			int oldCountStart) {
		super(ctx, datas);
		oldCount = oldCountStart;
		// Log.e("oldCunt", oldCount + ":sdfdsfd");
	}

	@Override
	public int getItemViewType(int p) {
		return TYPE_ARTICLE;

	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}

	@Override
	public int getCount() {
		if (datas != null && datas.size() > 0) {
			return datas.size();
		} else {
			return 0;
		}
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder_article viewHolder_article = null;
		int type = getItemViewType(position);
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_recommend_article,
					parent, false);
			viewHolder_article = new ViewHolder_article(convertView);
			convertView.setTag(viewHolder_article);
		} else {
			viewHolder_article = (ViewHolder_article) convertView.getTag();

		}
		if (type == TYPE_ARTICLE) {
			viewHolder_article.refreshView(datas.get(position), position);
		}

		return convertView;
	}

	public class ViewHolder_article implements View.OnClickListener {
		public ImageView imgArticlePic;
		TextView tvArticleTitle;
		TextView tvLike;
		ImageView ivTitle;
		FrameLayout title;
		public MLArticle item;
		public View parent;

		public ViewHolder_article(View parent) {
			this.parent = parent;
			initView(parent);
		}

		public ViewHolder_article() {
		}

		public void initView(View parent) {
			imgArticlePic = (ImageView) parent.findViewById(R.id.imgArticlePic);
			tvArticleTitle = (TextView) parent
					.findViewById(R.id.tvArticleTitle);
			tvLike = (TextView) parent.findViewById(R.id.tvLike);
			title = (FrameLayout) parent.findViewById(R.id.title);
			ivTitle = (ImageView) parent.findViewById(R.id.ivTitle);
		}

		public void refreshView(MLArticle item, int i) {
			this.item = item;
			if (i == 0 && oldCount != 0) {
				// ivTitle.setImageResource(R.drawable.home_update);
				Picasso.with(MLApplication.getContext())
						.load(R.drawable.home_update).into(ivTitle);
				title.setVisibility(View.VISIBLE);
			} else if (i == oldCount) {
				Picasso.with(MLApplication.getContext())
						.load(R.drawable.home_past).into(ivTitle);
				title.setVisibility(View.VISIBLE);
			} else {
				title.setVisibility(View.GONE);
			}
			// 设置图片
			String avatar = item.getTitleImgUrl();
			if (avatar != null && !avatar.equals("")) {
				// UserService.displaySquareRecommend(avatar, imgArticlePic);
				Transformation transformation = new RoundedTransformationBuilder()
						.cornerRadiusDp(5).oval(false).build();

//				Picasso.with(MLApplication.getContext()).load(avatar)
//						.placeholder(R.drawable.article_bg)
//						.transform(transformation).into(imgArticlePic);

				 UserService.displaySquareRecommend(avatar, imgArticlePic);
			} else {
				imgArticlePic.setImageResource(R.drawable.img_user_info_bg);
			}
			// 设置点赞次数,点赞红心
			Drawable drawble_left_press = ctx.getResources().getDrawable(
					R.drawable.btn_like_unpless); // 设置起始无红心
			drawble_left_press.setBounds(0, 0,
					drawble_left_press.getMinimumWidth(),
					drawble_left_press.getMinimumHeight());
			tvLike.setCompoundDrawables(null, null, drawble_left_press, null);
			// checkArticleLike(mlUser);
			if (MLApplication.getInstance().getIsLogin() == true) {
				checkSharepreference(item);
			}
			tvArticleTitle.setText(item.getTitle());
			tvLike.setText(String.valueOf(item.getLikeCount()));
			tvLike.setOnClickListener(this);
		}

		public void checkSharepreference(final MLArticle mlArticle) {
			if (MLContext.getArticleLikeSize("articleSize") == -1) { // 当sharepreference的数量为空时从网络获取
				final AVQuery<AVObject> query = new AVQuery<AVObject>(
						"MLArticleLike");
				query.whereEqualTo("article", mlArticle);
				query.whereEqualTo("user", UserService.getCurrentUser());
				query.setLimit(1000);
				// query.include("Article");
				query.findInBackground(new FindCallback<AVObject>() {
					@Override
					public void done(List<AVObject> list, AVException arg1) {
						if (arg1 == null) {
							if (list.size() > 0) {
								// Log.e("====未保存", "查询到点赞" + list.size()
								// + " 条符合条件的数据");
								tvLike.setText(String.valueOf(list.size()));
								for (AVObject tempUser : list) {
									MLArticleLike tempMLLike = (MLArticleLike) tempUser;
									if (tempMLLike.getArticle().equals(
											mlArticle)) {
										setLikeSb();
										MLContext.saveArticleLikeID(mlArticle
												.getObjectId());
										MLContext.saveLike(
												MLContext.LIKE_TYPE_RECOMMEND,
												mlArticle.getObjectId()
														.toString());
										Intent intent = new Intent();
										intent.setAction(Main.ACTION_LIKE_RECOMMEND);
										ctx.sendBroadcast(intent);

										break;
									}
								}
							} else {
								MLContext.getInstance().setAticleLikeSizeZero();
							}
						} else {
							// Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());

						}

					}
				});
			} else { // 当sharepreference有点赞纪录时从本地获取
				// Log.e("=====", "本地有点赞纪录");
				if (MLContext.getArticleLikeID(mlArticle.getObjectId()) != 0) {
					setLikeSb();

				} else {
					setCancleLikeSb(); // 设置红心取消

				}

			}
		}

		public void update(final MLArticle mlArticle) {
			tvLike.setText(String.valueOf(mlArticle.getLikeCount()));
			if (MLContext.getArticleLikeID(mlArticle.getObjectId()) != 0) {
				setLikeSb();
			} else {
				setCancleLikeSb(); // 设置红心取消
			}
		}

		/*
		 * 喜欢该对象，并保存该数据到leanCloud
		 */
		private void likeSb(final MLArticle mlArticle) {
			tvLike.setClickable(false); // 正在点赞，不准重复点击
			likeCount = mlArticle.getLikeCount() + 1;
			mlArticle.increment("likeCount", 1);
			mlArticle.saveInBackground(new SaveCallback() {

				@Override
				public void done(AVException arg0) {
					if (arg0 == null) {
						item.setLikeCount(likeCount);
						tvLike.setClickable(true); // 可点击了
						setLikeSb(); // 喜欢该对象，设置红心
						tvLike.setText(String.valueOf(likeCount)); // 点赞数量加一
						MLContext.saveArticleLikeID(mlArticle.getObjectId());
						MLContext.saveLike(MLContext.LIKE_TYPE_RECOMMEND,
								mlArticle.getObjectId().toString());
						Intent intent = new Intent();
						intent.setAction(Main.ACTION_LIKE_RECOMMEND);
						ctx.sendBroadcast(intent);

					} else {
						tvLike.setClickable(true); // 可点击了
						// Log.e("====", "点赞失败: " + arg0.getMessage());
					}
				}
			});
		}

		/*
		 * 喜欢该对象，在MLArticleLike表上添加或者删除纪录
		 */
		private void setMLArticleLike(final MLArticle mlArticle) {
			final AVQuery<AVObject> query = new AVQuery<AVObject>(
					"MLArticleLike");
			MLUser mlUser=new MLUser();
			mlUser.setObjectId(UserService.getCurrentUserId());
			query.whereEqualTo("article", mlArticle);
			query.whereEqualTo("user", mlUser);
			query.findInBackground(new FindCallback<AVObject>() {
				public void done(List<AVObject> avObjects, AVException e) {
					if (e == null) {
						if (avObjects.size() <= 0) { // 当用户以前没有喜欢过，则喜欢该对象
							// likeSb(user); // 喜欢该对象，并保存该数据到leanCloud

							MLArticleLike like = new MLArticleLike();
							like.setUser(UserService.getCurrentUser());
							like.setArticle(mlArticle);
							like.saveInBackground(new SaveCallback() {

								@Override
								public void done(AVException arg0) {
									if (arg0 == null) {
										likeSb(mlArticle);
										AVAnalytics.onEvent(ctx, "文章喜欢");
									} else {
										tvLike.setClickable(true); // 可点击了
										// Log.e("==mllike ", "Save failed."
										// + arg0.getMessage());

									}

								}
							});
						} else { // 当用户已经喜欢过，则取消喜欢
							query.deleteAllInBackground(
									new DeleteCallback() {

										@Override
										public void done(AVException arg0) {
											if (arg0 == null) {
												unLikeSb(mlArticle);
//												setCancleLikeSb(); // 设置红心取消
											} else {
												tvLike.setClickable(true); // 可点击了
												// Log.e("删除失败",
												// "查询错误: "
												// + arg0.getMessage());
											}

										}
									});
						}
					} else {
						tvLike.setClickable(true); // 可点击了
						// Log.e("失败", "查询错误: " + e.getMessage());

					}
				}
			});

		}

		/*
		 * 喜欢该对象，设置红心
		 */
		private void setLikeSb() {
			// Drawable drawble_left_press = ctx.getResources().getDrawable(
			// R.drawable.btn_like_pless); // 取消点赞红心
			// drawble_left_press.setBounds(0, 0,
			// drawble_left_press.getMinimumWidth(),
			// drawble_left_press.getMinimumHeight());
			// tvLike.setCompoundDrawables(null, null, drawble_left_press,
			// null);
			tvLike.setBackgroundResource(R.drawable.shape_rectangle_love);

		}

		/*
		 * 取消喜欢该对象，设置红心取消
		 */
		private void setCancleLikeSb() {
			// Drawable drawble_left_press = ctx.getResources().getDrawable(
			// R.drawable.btn_like_unpless); // 取消点赞红心
			// drawble_left_press.setBounds(0, 0,
			// drawble_left_press.getMinimumWidth(),
			// drawble_left_press.getMinimumHeight());
			// tvLike.setCompoundDrawables(null, null, drawble_left_press,
			// null);
			tvLike.setBackgroundResource(R.drawable.shape_rectangle_cancle_love);

		}

		/*
		 * 不喜欢该对象，并保存该数据到leanCloud
		 */
		private void unLikeSb(final MLArticle mlArticle) {
			tvLike.setClickable(false); // 正在点赞，不准重复点击
			likeCount = mlArticle.getLikeCount() - 1;
			mlArticle.increment("likeCount", -1);
			mlArticle.saveInBackground(new SaveCallback() {

				@Override
				public void done(AVException arg0) {
					if (arg0 == null) {
						item.setLikeCount(likeCount);
						tvLike.setClickable(true); // 可点击了
						setCancleLikeSb(); // 不喜欢该对象，取消红心
						tvLike.setText(String.valueOf(likeCount)); // 点赞数量减一
						MLContext.deleteArticleLikeID(mlArticle.getObjectId());
						MLContext.deleteLike(MLContext.LIKE_TYPE_RECOMMEND,
								mlArticle.getObjectId().toString());
					} else {
						tvLike.setClickable(true); // 可点击了
						// Log.e("====", "取消点赞失败: " + arg0.getMessage());
					}
				}
			});
		}

		@Override
		public void onClick(View v) {
			if (v.equals(tvLike)) {
				// 这里要保存点赞到leanCloud和shareprefreence
				if (MLApplication.getInstance().isLogin == false) {
					ToolKits.toast(ctx, "请先登录");
					return;
				}
				final MLArticle mlArticle = item;
//				if (MLContext.getArticleLikeID(mlArticle.getObjectId()) != 0) { // 当用户已经被点赞过,则取消点赞
//					unLikeSb(mlArticle); // 不喜欢该对象
//				} else { // 当用户没点赞过,则点赞
//					likeSb(mlArticle); // 喜欢该对象，并保存该数据到leanCloud
//					AVAnalytics.onEvent(ctx, "文章喜欢");
//				}
				tvLike.setClickable(false); // 正在点赞，不准重复点击
				setMLArticleLike(mlArticle); // 在MLLike表上添加或者删除纪录
			}
		}
	}

}
